<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);

/**
 * 聊天主逻辑
 * 主要是处理 onMessage onClose
 */

use \GatewayWorker\Lib\Gateway;

class Events
{
	// 当有客户端连接时，将client_id返回，让mvc框架判断当前uid并执行绑定
	public static function onConnect($client_id)
	{
		Gateway::sendToClient($client_id, json_encode(array(
        'type' => 'init',
        'client_id' => $client_id
    )));
	}

	/**
	 * 有消息时
	 * @param int $client_id
	 * @param mixed $message
	 */
	public static function onMessage($client_id, $message)
	{

		// 连接队列服务，ip地址为队列服务端ip，这里假设是本机部署ip为127.0.0.1
		$client = stream_socket_client("tcp://127.0.0.1:1238", $err_no, $err_msg, 5);
		if(!$client)
		{
		    exit($err_msg);
		}
		// 执行任务
		$queue_msg = array(
		    'class' => 'Worker',
		    'method' => 'operateData',
		    'args' => array($message),
		);
		// 数据末尾加一个换行，使其符合Text协议。使用json编码
		$queue_msg = json_encode($queue_msg)."\n";
		// 向队列发送任务，让队列慢慢去执行
		fwrite($client, $queue_msg);
		// 队列返回的结果，这个结果是立即返回的
		echo fread($client, 8192);
		fclose($client);







//		//以下的业务全部放到APP下的worker文件下的inDB函数内
//		$messageArr = explode(',', $message);
//
//
//
//
//
//
//		$model = M("ws");
//
//		$IMEI = $messageArr[1];
//
//		$order_type = $messageArr[2];
//
//		$order_code = $messageArr[3];
//
//		$is_exist = M('ws')->where(['client_id' => $client_id, 'imei' => $IMEI])->find();
//		if (!$is_exist) {
//			$insert_data = [
//				'client_id' => $client_id,
//				'imei' => $IMEI,
//				'create_time' => time()
//			];
//			$model->add($insert_data);
//
//			Gateway::bindUid($client_id, $IMEI);
//		}
//
//
////		$message_content = msg_content('A10*', $IMEI);
////		Gateway::sendToClient($client_id, $message_content);
//
//		$model_car = M('car');
//
//		$model_car_attr = M('car_attr');
//
//		$model_car_location_record = M('car_location_record');
//
//
//		if ($order_type == 'AAA' && $order_code == 35) {//自动回调数据
//
//			$carInfo = $model_car->where(['equipment_no' => $IMEI])->find();
//			if (!empty($carInfo) && $messageArr[7]!='V') {
//
//				$model_car->where(['id'=>$carInfo])->setField('status','3');
//
//				$temArr = !empty($messageArr[23]) ? explode('|', $messageArr[23]) : [];
//
//
//                //获取GPS消息中的时间日期
//
//                $num_arr=str_split($messageArr[6]);
//                $now_time="20".$num_arr[0].$num_arr[1]."-".$num_arr[2].$num_arr[3]."-".$num_arr[4].$num_arr[5]." ".$num_arr[6].$num_arr[7].":".$num_arr[8].$num_arr[9].":".$num_arr[10].$num_arr[11];
//
//                //转换温感器的温度
//                $tamps=$messageArr[23];
//                if (!empty($tamps)){
//                    $tamps_arr=explode('|',$tamps);
//                    foreach ($tamps_arr as &$val){
//                        //获取后4位数字
//                        $temp=str_split($val);
//                        $temps=$temp[2].$temp[3].$temp[4].$temp[5];
//
//                        $nums=str_split(hexdec($temps));
//
//                        $val=$nums[0].$nums[1].".".$nums[2].$nums[3];
//                    }
//
//
//                }
//
//                //优化正常温度  -40~40
//                //一区温度
//                if (empty($tamps_arr[0])){
//                    $tamps_arr_one=M('car_attr')->where(['create_time'=>array('lt',strtotime($now_time)),'temperature_one'=>array('between','-40,40'),'car_id'=>$carInfo['id']])->order("id desc")->getField("temperature_one");
//                }else{
//                    if ($tamps_arr[0]<-40){
//                        $tamps_arr_one=M('car_attr')->where(['create_time'=>array('lt',strtotime($now_time)),'temperature_one'=>array('between','-40,40'),'car_id'=>$carInfo['id']])->order("id desc")->getField("temperature_one");
//
//                    }elseif ($tamps_arr[0]>40){
//                        $tamps_arr_one=M('car_attr')->where(['create_time'=>array('lt',strtotime($now_time)),'temperature_one'=>array('between','-40,40'),'car_id'=>$carInfo['id']])->order("id desc")->getField("temperature_one");
//                    }else{
//                        $tamps_arr_one=$tamps_arr[0];
//                    }
//                }
//
//                //二区温度
//                if (empty($tamps_arr[1])){
//                    $tamps_arr_two=M('car_attr')->where(['create_time'=>array('lt',strtotime($now_time)),'temperature_two'=>array('between','-40,40'),'car_id'=>$carInfo['id']])->order("id desc")->getField("temperature_two");
//                }else{
//                    if ($tamps_arr[1]<-40){
//                        $tamps_arr_two=M('car_attr')->where(['create_time'=>array('lt',strtotime($now_time)),'temperature_two'=>array('between','-40,40'),'car_id'=>$carInfo['id']])->order("id desc")->getField("temperature_two");
//
//                    }elseif ($tamps_arr[1]>40){
//                        $tamps_arr_two=M('car_attr')->where(['create_time'=>array('lt',strtotime($now_time)),'temperature_two'=>array('between','-40,40'),'car_id'=>$carInfo['id']])->order("id desc")->getField("temperature_two");
//                    }else{
//                        $tamps_arr_two=$tamps_arr[1];
//                    }
//                }
//
//                //三区温度
//                if (empty($tamps_arr[2])){
//                    $tamps_arr_three=M('car_attr')->where(['create_time'=>array('lt',strtotime($now_time)),'temperature_three'=>array('between','-40,40'),'car_id'=>$carInfo['id']])->order("id desc")->getField("temperature_three");
//                }else{
//                    if ($tamps_arr[2]<-40){
//                        $tamps_arr_three=M('car_attr')->where(['create_time'=>array('lt',strtotime($now_time)),'temperature_three'=>array('between','-40,40'),'car_id'=>$carInfo['id']])->order("id desc")->getField("temperature_three");
//
//                    }elseif ($tamps_arr[2]>40){
//                        $tamps_arr_three=M('car_attr')->where(['create_time'=>array('lt',strtotime($now_time)),'temperature_three'=>array('between','-40,40'),'car_id'=>$carInfo['id']])->order("id desc")->getField("temperature_three");
//                    }else{
//                        $tamps_arr_three=$tamps_arr[2];
//                    }
//                }
//
//                //四区温度
//                if (empty($tamps_arr[3])){
//                    $tamps_arr_four=M('car_attr')->where(['create_time'=>array('lt',strtotime($now_time)),'temperature_four'=>array('between','-40,40'),'car_id'=>$carInfo['id']])->order("id desc")->getField("temperature_four");
//                }else{
//                    if ($tamps_arr[3]<-40){
//                        $tamps_arr_four=M('car_attr')->where(['create_time'=>array('lt',strtotime($now_time)),'temperature_four'=>array('between','-40,40'),'car_id'=>$carInfo['id']])->order("id desc")->getField("temperature_four");
//
//                    }elseif ($tamps_arr[3]>40){
//                        $tamps_arr_four=M('car_attr')->where(['create_time'=>array('lt',strtotime($now_time)),'temperature_four'=>array('between','-40,40'),'car_id'=>$carInfo['id']])->order("id desc")->getField("temperature_four");
//                    }else{
//                        $tamps_arr_four=$tamps_arr[3];
//                    }
//                }
//
//
//                //外接电压
//                if (!empty($messageArr[18])){
//                    $voltage_sums=explode('|',$messageArr[18]);
//                    //取第5个值  16进制转10进制  取整
//                    $voltage_msg=hexdec($voltage_sums[4]);
//                    //公式计算电压  取整
//                    $voltage_now=round(($voltage_msg*3.3*16)/4096);
//                }
//
//                //停车时间
//                if (empty($messageArr[10])){
//                    $stop_time_tam=M('car_attr')->where(['speed'=>array('gt',0),'car_id'=>$carInfo['id']])->order("id desc")->find();
//                    $stop_time=strtotime($now_time)-$stop_time_tam['create_time'];
//                }else{
//                    $stop_time=0;
//                }
//
//                //今日里程数
//				if (!empty($messageArr[14])){
//                     $all_meal = $messageArr[14];
//					$map['car_id'] = $carInfo['id'];
//					$map['create_time'] = array('lt',strtotime(date('Y-m-d',strtotime($now_time))));
//
//					$lastInfo = $model_car_attr->where($map)->order('id desc')->find();
//
//					$now_meal=($all_meal-$lastInfo['all_mileage']);
//					$today_mileage = empty($lastInfo)?$all_meal:$now_meal;
//				}
//
//				$insert_data = [
//					'car_id' => $carInfo['id'],
//					'uid' => $carInfo['uid'],
//                    'all_mileage' => empty($messageArr[14])?0:$messageArr[14],
//					'speed' => empty($messageArr[10]) ? '' : $messageArr[10],
//					'electric' => '',
//					'humidity' => '',
//					'oil' => empty($messageArr[22]) ? '' : $messageArr[22],
////					'temperature_one' => empty($temArr[0]) ? '' : (int)substr($temArr[0],2,4),
////					'temperature_two' => empty($temArr[1]) ? '' : (int)substr($temArr[1],2,4),
////					'temperature_three' => empty($temArr[2]) ? '' : (int)substr($temArr[2],2,4),
////					'temperature_four' => empty($temArr[3]) ? '' : (int)substr($temArr[3],2,4),
//                    'temperature_one' =>empty($tamps_arr_one)?'':$tamps_arr_one,
//                    'temperature_two' => empty($tamps_arr_two)?'':$tamps_arr_two,
//                    'temperature_three' => empty($tamps_arr_three)?'':$tamps_arr_three,
//                    'temperature_four' =>empty($tamps_arr_four)?'':$tamps_arr_four,
//					'update_time' => '',
//					'cold_switch' => '',
//					'temperature_one_area' => empty($temArr[0]) ? '' : (int)substr($temArr[0],2,4),
//					'temperature_two_area' => empty($temArr[1]) ? '' : (int)substr($temArr[1],2,4),
//					'temperature_three_area' => empty($temArr[2]) ? '' : (int)substr($temArr[2],2,4),
//					'temperature_four_area' => empty($temArr[3]) ? '' : (int)substr($temArr[3],2,4),
//					'temperature_area' => '',
//					'humidity_one' => '',
//					'humidity_two' => '',
//					'humidity_three' => '',
//					'humidity_four' => '',
//					'all_m' => $messageArr[14],
//					'today_mileage' => empty($today_mileage) ? 0 : $today_mileage,
//					'status_time' => '',
//					'lng' => $messageArr[5],
//					'lat' => $messageArr[4],
//					'humidity_area' => '',
//					'create_time' => strtotime($now_time),
//					'stop_time' => $stop_time,
//					'door' => '',
//					'stop_address' => '',
//					'car_status' => '',
//					'voltage' => $voltage_now,
//					'electric_quantity' => '',
//				];
//
//
//				$operation = $model_car_attr->add($insert_data);
//
//				if ($operation){
//
//					$model_car_attr->where(['id'=>$operation])->setField('all_m',$messageArr[14]);
//
//				}
//
//				//获取GPS消息中的时间日期
//
//                $num_arr=str_split($messageArr[6]);
//                $create_time="20".$num_arr[0].$num_arr[1]."-".$num_arr[2].$num_arr[3]."-".$num_arr[4].$num_arr[5]." ".$num_arr[6].$num_arr[7].":".$num_arr[8].$num_arr[9].":".$num_arr[10].$num_arr[11];
//
//				$insert_data_location = [
//					'uid' => $carInfo['uid'],
//					'car_id' => $carInfo['id'],
//					'lng' => $messageArr[5],
//					'lat' => $messageArr[4],
//					'create_time' => strtotime($create_time),
//				];
//
//
//				$model_car_location_record->add($insert_data_location);
//
//
//			}
//		}
//
//
//		//出入围栏报警
//		if ($order_code==21 || $order_code==20){
//
//			$carInfo = $model_car->where(['equipment_no' => $IMEI])->find();
//
//			if (!empty($carInfo)){
//
//				$model_msg = M('message');
//
//				$model_car_enclosure = M('car_enclosure');
//				$model_car_enclosure_bind = M('car_enclosure_bind');
//
//				$bindInfo = $model_car_enclosure_bind->where(['car_id'=>$carInfo['id'],'number'=>$messageArr[19]])->find();
//
//				$type_text = $bindInfo['type'] == 1?'出区域报警':'入区域报警';
//
//				$msg_data = [
//					'uid'	=>	$carInfo['uid'],
//					'send_uid'	=>	'',
//					'title'	=>	'围栏报警',
//					'content'	=>	$type_text,
//					'read_time'	=>	'',
//					'is_read'	=>	'0',
//					'type'	=>	2,
//					'create_time'	=>	time(),
//					'car_id'	=>	$carInfo['id'],
//					'warning_type'	=>	$bindInfo['type'],//出，2 入
//				];
//
//
//				$add_id=$model_msg->add($msg_data);
//
//
//				$enclosure_insert_data = [
//					'car_id'	=>	$carInfo['id'],
//					'uid'	=>	$carInfo['uid'],
//					'intime'	=>	$bindInfo['type']==1?time():'',
//					'outtime'	=>	$bindInfo['type']==2?time():'',
//					'enclosure_id'	=>	$bindInfo['enclosure_id'],
//					'number'	=>	$messageArr[19],
//				];
//
//
//				$model_car_enclosure->add($enclosure_insert_data);
//			}
//
//		}
//		/**
//		 * 包标识符数据长度 $$E159,     0
//		 * IMEI 866856038824809,     1
//		 * 指令类型 AAA,              2
//		 * 事件代码 35,               3
//		 * 纬度 22.512645,            4
//		 * 经度 114.057101,           5
//		 * 日期和时间 171005001107,      6
//		 * 定位状态 V,                  7
//		 * 卫星个数 0,                  8
//		 * GSM信号强度 24,              9
//		 * 速度 0,                    10
//		 * 方向 0,                    11
//		 * 水平定位精度 0.0,              12
//		 * 海拔高度 0,                  13
//		 * 里程数 0,                   14
//		 * 运行时间 1449012,            15
//		 * 基站信息 460|0|1813|00000798,16
//		 * 输入 输出口状态 0000,           17
//		 * 模拟量输入口值 0002|0000|0000|019E|0803,18
//		 * 事件辅助消息 00000001,         19
//		 * 定制数据 ,                   20
//		 * 协议版本 3,                  21
//		 * 油量百分比 ,                  22
//		 * 温度传感器,                   23
//		 * 最大加速度值 41,               24
//		 *
//		 * 76*64
//		 */
//
//		// debug
//		echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id session:" . json_encode($_SESSION) . " onMessage:" . $message . "\n";


	}

	/**
	 * 当客户端断开连接时
	 * @param integer $client_id 客户端id
	 */
	public static function onClose($client_id)
	{
		// debug
		echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id onClose:''\n";

		M('ws')->where(['client_id' => $client_id])->delete();

		// 从房间的客户端列表中删除
		if (isset($_SESSION['room_id'])) {
			$room_id = $_SESSION['room_id'];
			$new_message = array('type' => 'logout', 'from_client_id' => $client_id, 'from_client_name' => $_SESSION['client_name'], 'time' => date('Y-m-d H:i:s'));
			Gateway::sendToGroup($room_id, json_encode($new_message));
		}
	}

}
